package org.study.hadoop.md.ch4;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.InputSampler;
import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.study.hadoop.md.util.MRDPUtils;

import java.io.IOException;
import java.util.Map;

/**
 * 全排序：StackOverflow数据集中的用户数据按账号的创建时间排序，现在按用户最近访问网站的时间对这些数据进行排序
 */
public class TotalOrderSorting extends Configured implements Tool {

    public static class ValueReducer extends Reducer<Text, Text, Text, NullWritable> {
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            for (Text text : values) {
                context.write(text, NullWritable.get());
            }
        }
    }

    public static class LastAccessDateMapper extends Mapper<Object, Text, Text, Text> {
        private Text outKey = new Text();

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            Map<String, String> parsed = MRDPUtils.transformXmlToMap(value.toString());
            String date = parsed.get("LastAccessDate");
            if (date != null) {
                outKey.set(date);
                context.write(outKey, value);
            }
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Path inputPath = new Path("user.txt");
        Path partitionFile = new Path("user" + "_partitions.lst");
        Path outputStage = new Path("user" + "_staging");
        Path outputOrder = new Path("out");
        FileSystem.get(getConf()).delete(outputOrder, true);
        FileSystem.get(getConf()).delete(outputStage, true);
        FileSystem.get(getConf()).delete(partitionFile, true);
        double sampleRate = Double.parseDouble("0.1");

        Job sampleJob = Job.getInstance(getConf(), "TotalOrderSortingStage");
        sampleJob.setJarByClass(TotalOrderSorting.class);
        sampleJob.setMapperClass(LastAccessDateMapper.class);
        sampleJob.setNumReduceTasks(0);

        sampleJob.setOutputKeyClass(Text.class);
        sampleJob.setOutputValueClass(Text.class);

        TextInputFormat.setInputPaths(sampleJob, inputPath);

        sampleJob.setOutputFormatClass(SequenceFileOutputFormat.class);
        SequenceFileOutputFormat.setOutputPath(sampleJob, outputStage);

        int code = sampleJob.waitForCompletion(true) ? 0 : 1;

        if (code == 0) {
            Job orderJob = Job.getInstance(getConf(), "TotalOrderSortingStage");
            orderJob.setJarByClass(TotalOrderSorting.class);

            orderJob.setMapperClass(Mapper.class);
            orderJob.setReducerClass(ValueReducer.class);

            orderJob.setNumReduceTasks(5);

            orderJob.setPartitionerClass(TotalOrderPartitioner.class);
            TotalOrderPartitioner.setPartitionFile(orderJob.getConfiguration(), partitionFile);

            orderJob.setOutputKeyClass(Text.class);
            orderJob.setOutputValueClass(Text.class);

            orderJob.setInputFormatClass(SequenceFileInputFormat.class);
            SequenceFileInputFormat.setInputPaths(orderJob, outputStage);

            TextOutputFormat.setOutputPath(orderJob, outputOrder);

            orderJob.getConfiguration().set("mapred.textoutputformat.separator", "");

            InputSampler.writePartitionFile(orderJob, new InputSampler.RandomSampler(sampleRate, 10));

//            FileSystem.get(getConf()).delete(partitionFile, false);
//            FileSystem.get(getConf()).delete(outputStage, true);
            return orderJob.waitForCompletion(true) ? 0 : 2;
        }
        return code;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new TotalOrderSorting(), args);
        System.exit(res);
    }
}
